import os
import re
import requests
from concurrent.futures import ThreadPoolExecutor
import threading
import datetime

class BaiduImageDownloader:
    def __init__(self):
        self.word = None
        self.max_page = None
        self.folder_path = None
        self.headers = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36 Edg/136.0.0.0",
            "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
        }
        self.num = 1
        self.lock = threading.Lock()
        
    def get_current_date(self):
        # 获取当前日期并格式化为250603形式
        current_date = datetime.datetime.now()
        return current_date.strftime("%y%m%d")

    def baidu_search(self):
        self.word = input("请输入搜索内容：")
        max_page_input = input("请输入要下载的最大页数（默认1页）：")
        self.max_page = int(max_page_input) if max_page_input.strip() else 1

        # 创建文件夹
        self.folder_path = os.path.join(os.getcwd(), self.word)
        if not os.path.exists(self.folder_path):
            os.makedirs(self.folder_path)
            print(f"成功创建文件夹 {self.folder_path}")
        else:
            print(f"文件夹 {self.folder_path} 已存在")

        with ThreadPoolExecutor() as executor:
            for page in range(1, self.max_page + 1):
                url = f"https://image.baidu.com/search/index?tn=baiduimage&fm=result&ie=utf-8&word={self.word}&pn={(page - 1) * 30}"
                try:
                    response = requests.get(url, headers=self.headers)
                    response.raise_for_status()
                except requests.RequestException as e:
                    print(f"请求第 {page} 页失败: {e}")
                    continue

                img_urls = re.findall(r'"thumburl":"(https?://[^"]+)"', response.text)

                if not img_urls:
                    print(f"第 {page} 页未找到图片链接，停止下载。")
                    break

                futures = []
                for i in img_urls:
                    future = executor.submit(self.download_image, i)
                    futures.append(future)
                    self.num += 1

                # 等待当前页图片下载完成
                for future in futures:
                    future.result()

    def download_image(self, img_url):
        try:
            img_url = img_url.replace(r"\u0026", "&")
            img_response = requests.get(img_url, headers=self.headers)
            img_response.raise_for_status()
            # 确保线程安全
            with self.lock:
                date_str = self.get_current_date()
                file_name = f"{self.word}_{date_str}_{self.num}.jpg"
                self.num += 1
            # 将图片保存到新创建的文件夹中
            with open(os.path.join(self.folder_path, file_name), "wb") as f:
                # 写入图片内容
                f.write(img_response.content)
            print(f"成功下载图片 {file_name} 到 {self.folder_path}")
        except Exception as e:
            print(f"下载图片 {img_url} 失败: {e}")

if __name__ == "__main__":
    downloader = BaiduImageDownloader()
    downloader.baidu_search()